import 'package:flutter/material.dart';

class CartIndex extends StatefulWidget {
  const CartIndex({super.key});

  @override
  State<CartIndex> createState() => CartIndexState();
}

class CartIndexState extends State<CartIndex> {
  final List<Map<String, dynamic>> products = [
    {
      'name': '【精致可爱】高钢鸡蛋碗不锈钢饭盒',
      'image':
          'https://ts3.tc.mm.bing.net/th/id/OIP-C.MK_lxgnnVjHGRJdwiVHnNAAAAA?r=0&pid=ImgDet&w=400&h=400&rs=1',
      // 替换为有效的图片链接
      'price': 20,
      'quantity': 1,
    },
    {
      'name': '【31只勺子】厨房不锈钢勺',
      'image':
          'https://ts3.tc.mm.bing.net/th/id/OIP-C.MK_lxgnnVjHGRJdwiVHnNAAAAA?r=0&pid=ImgDet&w=400&h=400&rs=1',
      // 替换为有效的图片链接
      'price': 20,
      'quantity': 2,
    },
    {
      'name': '华为荣耀X10 5G手机',
      'image':
          'https://ts3.tc.mm.bing.net/th/id/OIP-C.MK_lxgnnVjHGRJdwiVHnNAAAAA?r=0&pid=ImgDet&w=400&h=400&rs=1',
      // 替换为有效的图片链接
      'price': 1999,
      'quantity': 1,
    },
  ];

  final List<Map<String, dynamic>> recommendedProducts = [
    {
      'name': '【推荐】不锈钢厨房套装不锈钢厨房套装不锈钢厨房套装不锈钢厨房套装',
      'image':
          'https://ts3.tc.mm.bing.net/th/id/OIP-C.MK_lxgnnVjHGRJdwiVHnNAAAAA?r=0&pid=ImgDet&w=400&h=400&rs=1',
      // 替换为有效的图片链接
      'price': 150,
      'quantity': 1,
    },
    {
      'name': '【热销】5G手机壳不锈钢厨房套装不锈钢厨房套装不锈钢厨房套装',
      'image':
          'https://ts3.tc.mm.bing.net/th/id/OIP-C.MK_lxgnnVjHGRJdwiVHnNAAAAA?r=0&pid=ImgDet&w=400&h=400&rs=1',
      // 替换为有效的图片链接
      'price': 50,
      'quantity': 1,
    },
    {
      'name': '【推荐】不锈钢厨房套装不锈钢厨房套装不锈钢厨房套装不锈钢厨房套装',
      'image':
          'https://ts3.tc.mm.bing.net/th/id/OIP-C.MK_lxgnnVjHGRJdwiVHnNAAAAA?r=0&pid=ImgDet&w=400&h=400&rs=1',
      // 替换为有效的图片链接
      'price': 150,
      'quantity': 1,
    },
    {
      'name': '【热销】5G手机壳不锈钢厨房套装不锈钢厨房套装不锈钢厨房套装',
      'image':
          'https://ts3.tc.mm.bing.net/th/id/OIP-C.MK_lxgnnVjHGRJdwiVHnNAAAAA?r=0&pid=ImgDet&w=400&h=400&rs=1',
      // 替换为有效的图片链接
      'price': 50,
      'quantity': 1,
    },
    {
      'name': '【推荐】不锈钢厨房套装不锈钢厨房套装不锈钢厨房套装不锈钢厨房套装',
      'image':
          'https://ts3.tc.mm.bing.net/th/id/OIP-C.MK_lxgnnVjHGRJdwiVHnNAAAAA?r=0&pid=ImgDet&w=400&h=400&rs=1',
      // 替换为有效的图片链接
      'price': 150,
      'quantity': 1,
    },
    {
      'name': '【热销】5G手机壳不锈钢厨房套装不锈钢厨房套装不锈钢厨房套装',
      'image':
          'https://ts3.tc.mm.bing.net/th/id/OIP-C.MK_lxgnnVjHGRJdwiVHnNAAAAA?r=0&pid=ImgDet&w=400&h=400&rs=1',
      // 替换为有效的图片链接
      'price': 50,
      'quantity': 1,
    },
  ];

  List<bool> selectedItems = [];

  void _addToCart(int index) {
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(SnackBar(content: Text('已添加到购物车')));
  }

  void _updateQuantity(int index, int delta) {
    setState(() {
      products[index]['quantity'] =
          (products[index]['quantity'] as int) + delta;
      if (products[index]['quantity'] <= 0) {
        products.removeAt(index);
        selectedItems.removeAt(index); // 同步移除选中状态
      }
    });
  }

  void _toggleSelection(int index) {
    setState(() {
      selectedItems[index] = !selectedItems[index];
    });
  }

  void _toggleAllSelection() {
    setState(() {
      bool newValue =
          !selectedItems.isNotEmpty || selectedItems.every((s) => s);
      selectedItems = List<bool>.filled(products.length, newValue);
    });
  }

  @override
  void initState() {
    super.initState();
    selectedItems = List<bool>.filled(products.length, false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(child: Text('购物车')),
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.more_vert),
            onPressed: () {
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(SnackBar(content: Text('更多功能')));
            },
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              width: MediaQuery.of(context).size.width,
              height: 40,
              color: Colors.white,
              child: Row(
                children: [
                  Expanded(
                    flex: 3,
                    child: TextButton(
                      onPressed: () {},
                      style: TextButton.styleFrom(
                        alignment: Alignment.centerLeft, // 设置按钮内容靠左对齐
                      ),
                      child: Row(
                        children: [
                          Icon(Icons.location_on, color: Colors.grey), // 添加地址图标
                          SizedBox(width: 5),
                          Text('地球村中国心'),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 10, // 设置分隔符的宽度
                    child: Center(
                      child: Text(
                        '|',
                        style: TextStyle(
                          color: Colors.grey, // 设置分隔符的颜色
                          fontSize: 18, // 设置分隔符的字体大小
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: TextButton(
                      onPressed: () {
                        Navigator.pushNamed(context, '/profile/address/index');
                      },
                      child: Text('切换地址'),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 10),
            ListView.builder(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              itemCount: products.length,
              itemBuilder: (context, index) {
                final product = products[index];
                return ListTile(
                  key: ValueKey(product['name']),
                  leading: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Checkbox(
                        value: selectedItems[index],
                        onChanged: (bool? value) => _toggleSelection(index),
                        activeColor: Colors.blue,
                      ),
                      Image.network(
                        product['image'],
                        width: 60,
                        height: 60,
                        fit: BoxFit.cover,
                      ),
                    ],
                  ),
                  title: Text(product['name']),
                  subtitle: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('¥${product['price']}'),
                      Positioned(
                        left: 0,
                        top: 0,
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            IconButton(
                              icon: Icon(Icons.remove),
                              onPressed: () => _updateQuantity(index, -1),
                            ),
                            Text('${product['quantity']}'),
                            IconButton(
                              icon: Icon(Icons.add),
                              onPressed: () => _updateQuantity(index, 1),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),

                  onTap: () => _addToCart(index),
                );
              },
            ),
            Container(
              width: MediaQuery.of(context).size.width,
              height: 30,
              color: Colors.grey.shade100,
              child: Center(child: Text('可能感兴趣的商品')),
            ),
            SizedBox(height: 8),
            GridView.builder(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2, // 设置为两列
                crossAxisSpacing: 10, // 列间距
                mainAxisSpacing: 10, // 行间距
                childAspectRatio: 1, // 控制子项的宽高比
              ),
              itemCount: recommendedProducts.length,
              itemBuilder: (ctx, i) {
                final recommended = recommendedProducts[i];
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Image.network(
                      recommended['image'],
                      height: 99, // 图片高度
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) =>
                          Icon(Icons.error), // 处理图片加载失败
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            recommended['name'],
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          Text(
                            '¥${recommended['price']}',
                            style: TextStyle(color: Colors.red),
                          ),
                        ],
                      ),
                    ),
                  ],
                );
              },
            ),
          ],
        ),
      ),
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Row(
              children: [
                Checkbox(
                  value: selectedItems.every((s) => s),
                  onChanged: (bool? value) => _toggleAllSelection(),
                  activeColor: Colors.blue,
                ),
                Text('全选'),
              ],
            ),
            Row(
              children: [
                Text('已选 ${selectedItems.where((s) => s).length} 件,合计: '),
                Text(' ¥', style: TextStyle(color: Colors.red)),
              ],
            ),
            ElevatedButton(
              style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
              onPressed: () {
                // 结算逻辑
              },
              child: Text('去结算', style: TextStyle(color: Colors.white)),
            ),
          ],
        ),
      ),
    );
  }
}
